/**
 * 
 */
package worklog;

import java.io.*; 
import java.sql.Date;
import java.util.Calendar;
import java.util.Locale;

import javax.xml.transform.*;    
import javax.xml.transform.dom.DOMSource;    
import javax.xml.transform.stream.StreamResult;        
import javax.xml.parsers.*;    
import org.w3c.dom.*; 
import org.xml.sax.InputSource;

/**
 * @author qren
 *
 */
public class DocGen {
	
	   /**1、将XML文件的内容转化为String 
	    * doc2String 
	    * 将xml文档内容转为String 
	    * @return 字符串 
	    * @param document 
	    */ 
	   public static String doc2String(Document document) 
	   { 
	      String s = ""; 
	      try 
	      { 
	          TransformerFactory tFactory = TransformerFactory.newInstance();    
	          Transformer transformer = tFactory.newTransformer(); 
	          /** 使用GB2312编码 */ 
	          //transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312"); 
	          Source source = new DOMSource( document );             
	          /** 直接输出到控制台 */ 
	          //Result output = new StreamResult( System.out );          
	          StringWriter out = new StringWriter();  
	          Result output = new StreamResult( out ); 
	          transformer.transform( source, output ); 
	          out.flush(); 
	          s = out.toString(); 
	      }catch(Exception ex) 
	      {             
	          ex.printStackTrace(); 
	      }       
	      return s; 
	   }
	   
	   /**2、将符合XML格式的String 转化为XML Document

	    * string2Document 
	    * 将字符串转为Document 
	    * @return  
	    * @param s xml格式的字符串 
	    */ 
	   public static Document string2Document(String s) 
	   { 
	      Document document = null; 
	      try 
	      { 
	          DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
	          document = parser.parse( new InputSource(new StringReader(s)) ); 
	      }catch(Exception ex) 
	      {             
	           ex.printStackTrace(); 
	      } 
	      return document; 
	   }
	
	   /**3、将Document对象保存为一个xml文件到本地 
	    * doc2XmlFile 
	    * 将Document对象保存为一个xml文件到本地 
	    * @return true:保存成功  flase:失败 
	    * @param filename 保存的文件名 
	    * @param document 需要保存的document对象 
	    */ 
	   public static boolean doc2XmlFile(Document document,String filename) 
	   { 
	      boolean flag = true; 
	      try 
	      { 
	            /** 将document中的内容写入文件中  */ 
	            TransformerFactory tFactory = TransformerFactory.newInstance();    
	            Transformer transformer = tFactory.newTransformer();  
	            /** 编码 */ 
	            //transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312"); 
	            DOMSource source = new DOMSource(document);  
	            StreamResult result = new StreamResult(new File(filename));    
	            transformer.transform(source, result);  
	        }catch(Exception ex) 
	        { 
	            flag = false; 
	            ex.printStackTrace(); 
	        } 
	        return flag;       
	   }
	
	   /**4、将xml格式的字符串保存为本地文件，如果字符串格式不符合xml规则，则返回失败 
	    * string2XmlFile 
	    * 将xml格式的字符串保存为本地文件，如果字符串格式不符合xml规则，则返回失败 
	    * @return true:保存成功  flase:失败 
	    * @param filename 保存的文件名 
	    * @param str 需要保存的字符串 
	    */ 
	   public static boolean string2XmlFile(String str,String filename) 
	   { 
	      boolean flag = true; 
	      /* 以下格式生成的文件是以UTF-8为格式 */ 
	      try 
	      { 
	         Document doc = string2Document(str);        
	         flag = doc2XmlFile(doc,filename); 
	      }catch (Exception ex) 
	      { 
	         flag = false; 
	         ex.printStackTrace(); 
	      } 
	      /** 以下不通过xml格式验证，象生成普通文件格式的方法生成xml文件 
	        OutputStream os = null;        
	        try { 
	                os = new FileOutputStream(filename); 
	                os.write(str.getBytes()); 
	                os.flush(); 
	        } catch (Exception ex) { 
	                flag = false; 
	                ex.printStackTrace(); 
	        }finally 
	        {      
	              try{  
	                if (os!=null) os.close(); 
	              }catch (Exception ex) { 
	                ex.printStackTrace(); 
	              }               
	        } 
	         */ 
	      return flag; 
	   }
	
	   /**5、载入一个xml文档 
	    * load 
	    * 载入一个xml文档 
	    * @return 成功返回Document对象，失败返回null 
	    * @param uri 文件路径 
	    */ 
	   public static Document load(String filename) 
	   { 
	      Document document = null; 
	      try  
	      {  
	           DocumentBuilderFactory  factory = DocumentBuilderFactory.newInstance();    
	           DocumentBuilder builder=factory.newDocumentBuilder();    
	           document=builder.parse(new File(filename));    
	           document.normalize(); 
	      } 
	      catch (Exception ex){ 
	          ex.printStackTrace(); 
	      }   
	      return document; 
	   }
	
	   /**6、演示String保存为xml文件 
	    * xmlWriteDemoByString 
	    * 演示String保存为xml文件 
	    */ 
	   public void xmlWriteDemoByString() 
	   { 
	      String s = ""; 
	      /** xml格式标题 "<?xml version='1.0' encoding='GB2312'?>" 可以不用写*/ 
	      s = "<?xml version='1.0' encoding='GB2312'?>" 
	         +"<config>\r\n" 
	         +"   <ftp name='DongDian'>\r\n" 
	         +"     <ftp-host>127.0.0.1</ftp-host>\r\n" 
	         +"     <ftp-port>21</ftp-port>\r\n" 
	         +"     <ftp-user>cxl</ftp-user>\r\n" 
	         +"     <ftp-pwd>longshine</ftp-pwd>\r\n" 
	         +"     <!-- ftp最多尝试连接次数 -->\r\n" 
	         +"     <ftp-try>50</ftp-try>\r\n" 
	         +"     <!-- ftp尝试连接延迟时间 -->\r\n" 
	         +"     <ftp-delay>10</ftp-delay>\r\n" 
	         +"     <ftp-chn>中文</ftp-chn>\r\n" 
	         +"  </ftp>\r\n" 
	         +"</config>\r\n"; 
	      //将文件生成到classes文件夹所在的目录里    
	      string2XmlFile(s,"xmlWriteDemoByString.xml");    
	      //将文件生成到classes文件夹里    
	      string2XmlFile(s,"classes/xmlWriteDemoByString.xml");   
	   }
	
	   /** 
	    * 演示手动创建一个Document，并保存为XML文件 
	    */ 
	   public void xmlWriteDemoByDocument() 
	   { 
	        /** 建立document对象 */ 
	        try  
	        {  
	           DocumentBuilderFactory  factory = DocumentBuilderFactory.newInstance(); 
	           DocumentBuilder builder = factory.newDocumentBuilder(); 

	           Document document = builder.newDocument(); 
	           /** 建立config根节点 */ 
	           Element configElement = document.createElement("config"); 
	           document.appendChild( configElement ); 
	           /** 建立ftp节点 */ 
	           Comment cmt = document.createComment("东电ftp配置");         
	           configElement.appendChild(cmt);         
	        
	           Element ftpElement = document.createElement("ftp"); 
	           configElement.appendChild(ftpElement); 
	           ftpElement.setAttribute("name","DongDian"); 
	           /** ftp 属性配置 */ 
	           Element element = document.createElement("ftp-host"); 
	           element.appendChild(document.createTextNode( "127.0.0.1" )); 
	           ftpElement.appendChild(element); 
	            
	           element = document.createElement("ftp-port"); 
	           element.appendChild(document.createTextNode( "21" )); 
	           ftpElement.appendChild(element); 
	            
	           element = document.createElement("ftp-user"); 
	           element.appendChild(document.createTextNode( "cxl" )); 
	           ftpElement.appendChild(element); 
	            
	           element = document.createElement("ftp-pwd"); 
	           element.appendChild(document.createTextNode( "longshine" )); 
	           ftpElement.appendChild(element); 
	            
	           element = document.createElement("ftp-try"); 
	           element.appendChild(document.createTextNode( "50" )); 
	           ftpElement.appendChild(element); 
	            
	           element = document.createElement("ftp-chn"); 
	           element.appendChild(document.createTextNode( "中文" )); 
	           ftpElement.appendChild(element); 
	            
	           /** 保存Document */ 
	           doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml"); 
	      } 
	      catch (Exception ex){ 
	          ex.printStackTrace(); 
	      }        
	   }
	
	   /** 
	    *  演示读取文件的具体某个节点的值  
	    */ 
	   public static void xmlReadDemo() 
	   { 
	      Document document = load("classes/xmlWriteDemoByDocument.xml"); 
	      Node root=document.getDocumentElement(); 
	      /** 如果root有子元素 */ 
	      if(root.hasChildNodes()) 
	      { 
	         /** ftpnodes */ 
	         NodeList ftpnodes = root.getChildNodes(); 
	         /** 循环取得ftp所有节点 */ 
	         for (int i=0;i<ftpnodes.getLength();i++) 
	         { 
	            NodeList ftplist = ftpnodes.item(i).getChildNodes(); 
	            for (int k=0;k<ftplist.getLength();k++) 
	            { 
	              Node subnode = ftplist.item(k); 
	              if (subnode.getNodeType()==Node.ELEMENT_NODE) 
	              { 
	                /** 打印ftp所有节点属性的值 */ 
	                System.out.println(subnode.getNodeName()+":"+subnode.getFirstChild().getNodeValue()); 
	              } 
	            } 
	         } 
	      } 
	   }

	   /** 
	    *  演示修改文件的具体某个节点的值  
	    */ 
	   public static void xmlUpdateDemo() 
	   { 
	      Document document = load("classes/xmlWriteDemoByDocument.xml"); 
	      Node root=document.getDocumentElement(); 
	      /** 如果root有子元素 */ 
	      if(root.hasChildNodes()) 
	      { 
	         /** ftpnodes */ 
	         NodeList ftpnodes = root.getChildNodes(); 
	         /** 循环取得ftp所有节点 */ 
	         for (int i=0;i<ftpnodes.getLength();i++) 
	         {                       
	            NodeList ftplist = ftpnodes.item(i).getChildNodes(); 
	            for (int k=0;k<ftplist.getLength();k++) 
	            { 
	              Node subnode = ftplist.item(k); 
	              /** 删除ftp-chn节点 */ 
	              if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="ftp-chn") 
	              { 
	                 ftpnodes.item(i).removeChild(subnode); 
	              } 
	              /** 修改ftp-host的值为 192.168.0.1 */ 
	              if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="ftp-host") 
	              {                  
	                 subnode.getFirstChild().setNodeValue("192.168.0.1"); 
	              } 
	            } 
	             
	         } 
	      } 
	      /** 修改完后重新保存 */ 
	      doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml"); 
	   }
	   
	   public static String getDateStr(int d){
		   //Date startDate = Date.valueOf("2013-01-01");
		   Calendar cal = Calendar.getInstance();
		   //cal.clear();
		   cal.set(2012,11,28);
		   cal.add(Calendar.DAY_OF_MONTH, d);
		   
		   return //cal.get(Calendar.YEAR)+ "年"
				   getDisStr((cal.get(Calendar.MONTH)+1)) + "月"
				   + "-" + getDisStr(cal.get(Calendar.DAY_OF_MONTH))+"日"
		           + " " + cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.CHINESE);
	   }
	   public static String getDisStr(int m){
		   if(m<10)return " "+m;
		   return ""+m;
		   
	   }
	   public static void genWorklog() 
	   { 
	      Document document = load("log3.xml"); 
	      Node root=document.getDocumentElement(); 
	      /** 如果root有子元素 */ 
	      if(root.hasChildNodes()) 
	      { 
	         /** ftpnodes */ 
	         NodeList ftpnodes = root.getChildNodes(); 
	         /** 循环取得ftp所有节点 */ 
	         for (int i=0;i<ftpnodes.getLength();i++) 
	         {                       
	            NodeList ftplist = ftpnodes.item(i).getChildNodes(); 
	            for (int k=0;k<ftplist.getLength();k++) 
	            { 
	              Node subnode = ftplist.item(k); 
	              /** 删除ftp-chn节点 */ 
	              if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="ftp-chn") 
	              { 
	                 ftpnodes.item(i).removeChild(subnode);
	                 
	              } 
	              /** 修改ftp-host的值为 192.168.0.1 */ 
	              if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="ftp-host") 
	              {                  
	                 subnode.getFirstChild().setNodeValue("192.168.0.1"); 
	              } 
	            } 
	             
	         } 
	      } 
	      /** 修改完后重新保存 */ 
	      doc2XmlFile(document,"logGen.xml"); 
	   }
		public static Node getDateElem(Node sectElem) {
			
			return sectElem.getChildNodes().item(0).getChildNodes().item(4).getChildNodes().item(1);			
		}
		public static void replaceDateByDay(Node dateElem, int d) {
			dateElem.setTextContent(getDateStr(d));
						
		}
		public static NodeList genPageForDay(Node sectElem,Node dateElem, int d) {
			replaceDateByDay(dateElem,d);
			Node page = sectElem.cloneNode(true);
			//Node lastOne = page.getLastChild();
			//page.removeChild(lastOne);
			
			return page.getChildNodes();
						
		}
		/**
		 * @param args
		 */
		public static void main(String[] args) {
			//DocGen gen = new DocGen();
			
			//gen.xmlWriteDemoByDocument();
			 Document document = load("log3.xml"); 
		     Node root=document.getDocumentElement(); 
		     NodeList sects = document.getElementsByTagName("wx:sect");
		     Node sectElem = sects.item(0);
		     Node templateSectElem = sectElem.cloneNode(true);
		     templateSectElem.removeChild(templateSectElem.getLastChild());
		     Node dateElem = getDateElem(templateSectElem);
		     System.out.println(dateElem.getTextContent());
		     Node lastNode = sectElem.getLastChild();
		     //sectElem.insertBefore(null,null);
		     /*
		     for (int i=0;i<sects.getLength();i++) 
	         {  
		    	 System.out.println(sects.item(i).getNodeName());
	         }*/
		     
		     
			 for(int i=0;i<369;i++){
				System.out.println(getDateStr(i));
				NodeList page = genPageForDay(templateSectElem,dateElem,i);
				
				for(int j=0;j<page.getLength();j++){
					sectElem.insertBefore(page.item(j).cloneNode(true), lastNode);
				}
				
			 }
			 
			 doc2XmlFile(document,"logGen.xml"); 
		

		}	   
}
